import {ComponentType} from 'react'
import Taro, {Component, Config} from '@tarojs/taro'
import {View, Button, Image, Input, Form, Text} from '@tarojs/components'
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {companyName, getRuntime, isPhone, phoneNumPartOf, ServerHost} from "../../utils/common";

import './bindPhone.less'
import check from "../../assets/img/icon_06.png";
import check_on from "../../assets/img/icon_08.png";

interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class BindPhone extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    smsCode: '', // 短信验证码 ,
    phoneNumber: '', // 手机号码
    getCodeText: '获取验证码',
    btnCodeStatus: false,
    invitationCode: '',
    isAgree: false,
  }


  componentWillMount() {
    Taro.setNavigationBarTitle({title: '用户登录'})


    let userInfo = getRuntime().getUserInfo() || {}
    if(Object.keys(userInfo).length>0 && userInfo.avatar) {
      getRuntime().navigateTo('/pages/index/index');
    }

    let invitationCode = this.$router.params.invitationCode
    if(invitationCode) {
      this.setState({ invitationCode });
      getRuntime().setStorage('invitationCode', { invitationCode })
    }
  }

  componentDidShow(): void {
    Taro.setNavigationBarTitle({title: '用户登录'})
  }

  componentDidHide(): void {
  }

  link(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  changeInput(field: string, e) {
    this.setState({ [field]: e.detail.value })
  }

  getCode() {
    let { phoneNumber,btnCodeStatus } = this.state
    if(typeof btnCodeStatus === 'number') return
    if(!phoneNumber){getRuntime().showToast('请填写手机号~'); return false}
    if(!isPhone){getRuntime().showToast('请填写11位手机号码~'); return false}
    let { userStore } =  this.props.stores
    userStore.getSmsCode({
      form: {
        phoneNumber
      },callback: () => {
        this.countDown()
        getRuntime().showToast('验证码发送成功,请注意查收~')
      }
    })
  }

  // 验证码倒计时
  countDown() {
    let getCodeText = 60
    let timer = setInterval(() => {
      getCodeText--
      if(getCodeText===0){
        clearInterval(timer)
        this.setState({
          getCodeText: '获取验证码',
          btnCodeStatus: false,
        })
      }else {
        this.setState({
          getCodeText: getCodeText+'s',
          btnCodeStatus: true,
        })
      }
    },1000)
  }

  setAgree() {
    this.setState({ isAgree: !this.state.isAgree })
  }

  submit() {
    let { userStore } = this.props.stores
    let { smsCode, phoneNumber,invitationCode, isAgree } = this.state
   /* if(!invitationCode) {
      invitationCode = getRuntime().getStorage('invitationCode').invitationCode;
      Taro.removeStorageSync('invitationCode')
    }*/
    if(!phoneNumber){getRuntime().showToast('请填写手机号~'); return false}
    if(!smsCode){getRuntime().showToast('请填写验证码~'); return false}
    if(!isAgree) { getRuntime().showToast('请阅读并勾选用户服务协议~'); return false }
    userStore.userLogin({
      form: {
        sourceUserId: parseInt(invitationCode),
        smsCode,
        phoneNumber
      },
      callback: (res) => {
        getRuntime().setStorage('loginPage', { isLogin: true })
        getRuntime().setUserInfo(res);
        let url = ServerHost+'/api/Account/GetWechatCode'
        window.location.href = url
      }
    })
  }

  render() {
    let { btnCodeStatus,getCodeText,isAgree } = this.state
    return (
      <View className='edit-phone'>
        <View className='form-wrap'>
            <View className='content-30' style={{backgroundColor: '#fff'}}>
              <View className='form-wrap__group'>
                <View className='form-wrap__title'>手机号</View>
                <View className='form-wrap__content'>
                  <Input className='input' type='number' name='phoneNumber' placeholderClass='placeholder-class' placeholder='请输入手机号'
                         onChange={this.changeInput.bind(this,'phoneNumber')}
                  />
                </View>
              </View>
              <View className='form-wrap__group bbnone'>
                <View className='form-wrap__title'>验证码</View>
                <View className='form-wrap__content'>
                  <Input className='input' name='smsCode' placeholderClass='placeholder-class' placeholder='请输入短信验证码'
                         onChange={this.changeInput.bind(this,'smsCode')}
                  />
                  <Button className='get-code color-theme'  onClick={this.getCode.bind(this)} disabled={btnCodeStatus}>{getCodeText}</Button>
                </View>
              </View>
            </View>
            <View onClick={this.submit.bind(this)} className='circular-submit' style={{marginTop:'50px'}}>立即登录</View>

        </View>

        <View className='protocol' style={{justifyContent: 'flex-start'}}>
          {
            !isAgree&& <Image className='icon-check' src={check} onClick={this.setAgree.bind(this)} />
          }
          {
            isAgree&& <Image className='icon-check' src={check_on} onClick={this.setAgree.bind(this)} />
          }
          <Text className='protocol-text color-theme'  onClick={this.link.bind(this,'/pages/other/serviceAgreement')}>《{companyName}服务协议》</Text>
        </View>
      </View>
    )
  }
}

export default BindPhone
